package me.zxk.smartagriculture.service;

import lombok.extern.slf4j.Slf4j;
import me.zxk.smartagriculture.common.ErrorCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * 文件上传服务
 */
@Service
@Slf4j
public class FileUploadService {

    @Value("${file.upload.path:uploads/}")
    private String uploadPath;

    @Value("${file.upload.max-size:10485760}") // 10MB
    private long maxFileSize;

    @Value("${server.port:8080}")
    private String serverPort;

    @Value("${app.base-url:}")
    private String baseUrl;

    private static final List<String> ALLOWED_IMAGE_TYPES = Arrays.asList(
            "image/jpeg", "image/jpg", "image/png", "image/gif"
    );

    /**
     * 上传头像文件
     */
    public String uploadAvatar(MultipartFile file, Long userId) {
        validateFile(file);

        try {
            // 创建用户头像目录
            String avatarDir = uploadPath + "avatars/";
            File dir = new File(avatarDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = getFileExtension(originalFilename);
            String filename = userId + "_" + UUID.randomUUID().toString() + extension;

            // 保存文件
            Path filePath = Paths.get(avatarDir + filename);
            Files.write(filePath, file.getBytes());

            // 生成完整的文件URL
            String relativeUrl = "/uploads/avatars/" + filename;
            String fullUrl = getFullUrl(relativeUrl);

            log.info("头像上传成功: userId={}, relativeUrl={}, fullUrl={}", userId, relativeUrl, fullUrl);

            return fullUrl;
        } catch (IOException e) {
            log.error("头像上传失败: userId={}, error={}", userId, e.getMessage());
            throw new RuntimeException(ErrorCode.FILE_UPLOAD_ERROR.getMessage());
        }
    }

    /**
     * 验证文件
     */
    private void validateFile(MultipartFile file) {
        if (file.isEmpty()) {
            throw new RuntimeException("文件不能为空");
        }

        if (file.getSize() > maxFileSize) {
            throw new RuntimeException(ErrorCode.FILE_SIZE_ERROR.getMessage());
        }

        String contentType = file.getContentType();
        if (!ALLOWED_IMAGE_TYPES.contains(contentType)) {
            throw new RuntimeException(ErrorCode.FILE_TYPE_ERROR.getMessage());
        }
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String filename) {
        if (filename == null || filename.lastIndexOf(".") == -1) {
            return ".jpg";
        }
        return filename.substring(filename.lastIndexOf("."));
    }

    /**
     * 获取完整的文件URL
     */
    private String getFullUrl(String relativeUrl) {
        // 如果配置了自定义基础URL，使用自定义URL
        if (baseUrl != null && !baseUrl.trim().isEmpty()) {
            return baseUrl.endsWith("/") ? baseUrl + relativeUrl.substring(1) : baseUrl + relativeUrl;
        }

        // 否则使用默认的localhost地址
        return relativeUrl;
    }
}
